import React, {Component} from 'react';
import {connect} from 'dva';
import {Form, FormItem, Input, Button, Select, Radio, DatePicker, Upload, Modal, Icon} from 'antd';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import FooterToolbar from '@/components/FooterToolbar';
import {EditorState, convertToRaw, ContentState} from 'draft-js';
import {Editor} from 'react-draft-wysiwyg';
import draftToHtml from 'draftjs-to-html';
import 'react-draft-wysiwyg/dist/react-draft-wysiwyg.css'
import {HOST_URL, IMG_URL} from "../../utils/utils";
import moment from "moment";
import E from 'wangeditor'
import request from '@/utils/request';
export default @connect(({active, loading}) => ({
  active,
  loading: loading.effects['active/save'],
}))

@Form.create()
class ActiveEdit extends Component {
  state = {
    preview: '',
    visible: false,
    id: "",
    article_type: "",
    article_title:"",
    article_speaker:"",
    article_author:"",
    article_category:"",
    article_activityStartTime:"",
    article_activityEndTime:"",
    article_activityDownTime:"",
    article_tag:"",
    article_address:"",
    article_describe: "",
    imageList: [],
    editorState:"",
  }

  componentDidMount() {
    const articleID = this.props.match.params.id;
    const {dispatch} = this.props;
    dispatch({
      type: 'active/detail',
      payload: articleID
    });
    dispatch({
      type: 'active/fetchCategory',
      payload: {type: 'activity'},
    });
    const elem = this.refs.editorElem
    this.editor = new E(elem)
    this.editor.customConfig.onchange = html => {
      this.setState({
        editorState: html
      })
    }
    this.editor.customConfig.customUploadImg = function (files, insert) {
      console.log(files.length)
      request('/api/oss/sign/images', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json;',
        },
      }).then(OSSSign => {
        let timestamp3 = new Date().getTime();
        const xhr = new XMLHttpRequest();
        let ossData = new FormData();
        ossData.append('name', timestamp3 + "" + files[0].name);
        ossData.append('OSSAccessKeyId', OSSSign.accessId);
        ossData.append('policy', OSSSign.policy);
        ossData.append('Signature', OSSSign.signature);
        ossData.append('callback', OSSSign.callback);
        ossData.append('key', `${OSSSign.dir}${OSSSign.policy.substr(0, 16)}${files[0].name}`);
        ossData.append('success_action_status', "200"); // 指定返回的状态码
        ossData.append('file', files[0]);
        xhr.open('POST', OSSSign.host);
        xhr.send(ossData);
        xhr.addEventListener('load', () => {
          console.log('response==>' + xhr.responseText);
          if (xhr.responseText.indexOf("Error") != -1) {
            alert(xhr.responseText.indexOf("Error"))
          } else {
            const response = JSON.parse(xhr.responseText);
            if (response.filename) {
              insert(IMG_URL + response.filename)
            } else {
              alert('服务器异常');
            }
          }
        });
        xhr.addEventListener('error', () => {
          alert('服务器异常');
        });
      });
    }
    this.editor.customConfig.zIndex = 1
    this.editor.create();
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.active.detail && nextProps.active.detail.activityId) {
      if(!this.state.editorState){
        this.editor.txt.html(nextProps.active.detail.body);
      }
      this.setState({
        id: nextProps.active.detail.activityId,
        article_type: nextProps.active.detail.type,
        article_title: nextProps.active.detail.title,
        article_speaker:nextProps.active.detail.speaker,
        article_author:nextProps.active.detail.author,
        article_category:nextProps.active.detail.categorys[0],
        article_activityStartTime:nextProps.active.detail.activityStartTime,
        article_activityEndTime:nextProps.active.detail.activityEndTime,
        article_activityDownTime:nextProps.active.detail.activityDownTime,
        article_activityHoldTime:nextProps.active.detail.activityHoldTime,
        article_tag:nextProps.active.detail.tags&&nextProps.active.detail.tags.length>0?nextProps.active.detail.tags.join("，"):'',
        article_address:nextProps.active.detail.address,
        article_describe: nextProps.active.detail.summary,
        article_attendPrice: nextProps.active.detail.attendPrice/100,
        article_maxAttendCount: nextProps.active.detail.maxAttendCount,
        article_relatedActivity:nextProps.active.detail.relatedActivity,
        editorState:nextProps.active.detail.body,
        imageList: [{
          uid: 1,
          name: "name",
          status: "200",
          type: "type",
          result: "fileName",
          url: nextProps.active.detail.coverPic,
        }],
      })
    }
  }

  onEditorStateChange = (editorState) => {
    this.setState({
      editorState,
    });
  };
  addArticle = () => {
    const {dispatch, form} = this.props;
    form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        dispatch({
          type: 'active/save',
          payload: {
            articleId: this.state.id,
            article_pic: this.state.imageList.length == 0 ? "" : this.state.imageList[0].url,
            article_detail: this.state.editorState, ...values,
            article_activityStartTime: values.article_activityStartTime && moment(values.article_activityStartTime).format("YYYY-MM-DD HH:mm:ss"),
            article_activityEndTime: values.article_activityEndTime && moment(values.article_activityEndTime).format("YYYY-MM-DD HH:mm:ss"),
            article_activityDownTime: values.article_activityDownTime && moment(values.article_activityDownTime).format("YYYY-MM-DD HH:mm:ss"),
            article_activityHoldTime: values.article_activityHoldTime && moment(values.article_activityHoldTime).format("YYYY-MM-DD HH:mm:ss")
          },
        });
      }
    });
  }
  uploadImageCallBack = (file) => {
    return new Promise(
      (resolve, reject) => {
        request('/api/oss/sign/images', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json;',
          },
        }).then(OSSSign => {
          let timestamp3 = new Date().getTime();
          const xhr = new XMLHttpRequest();
          let ossData = new FormData();
          ossData.append('name', file.name);
          ossData.append('OSSAccessKeyId', OSSSign.accessId);
          ossData.append('policy', OSSSign.policy);
          ossData.append('Signature', OSSSign.signature);
          ossData.append('callback', OSSSign.callback);
          ossData.append('key', `${OSSSign.dir}${OSSSign.policy.substr(0, 16)}${file.name}`);
          ossData.append('success_action_status', "200"); // 指定返回的状态码
          ossData.append('file', file);
          xhr.open('POST', OSSSign.host);
          xhr.send(ossData);
          xhr.addEventListener('load', () => {
            console.log('response==>' + xhr.responseText);
            const response = JSON.parse(xhr.responseText);
            if (response.filename) {
              resolve({
                data: {
                  link: IMG_URL + response.filename,
                },
              });
            } else {
              reject('服务器异常');
            }
          });
          xhr.addEventListener('error', () => {
            reject('服务器异常');
          });
        });
      },
    );
  }
  beforeUpload = file => {
    let reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onloadend = () => {
      request('/api/oss/sign/images', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json;',
        },
      }).then(OSSSign => {
        let timestamp3 = new Date().getTime();
        const xhr = new XMLHttpRequest();
        let ossData = new FormData();
        ossData.append('name', file.name);
        ossData.append('OSSAccessKeyId', OSSSign.accessId);
        ossData.append('policy', OSSSign.policy);
        ossData.append('Signature', OSSSign.signature);
        ossData.append('callback', OSSSign.callback);
        ossData.append('key', `${OSSSign.dir}${OSSSign.policy.substr(0, 16)}${file.name}`);
        ossData.append('success_action_status', "200"); // 指定返回的状态码
        ossData.append('file', file);
        xhr.open('POST', OSSSign.host);
        xhr.send(ossData);
        xhr.addEventListener('load', () => {
          console.log('response==>' + xhr.responseText);
          const response = JSON.parse(xhr.responseText);
          if (response.filename) {
            this.setState(({ imageList }) => ({
              imageList: [{
                uid: file.uid,
                name: file.name,
                status: file.status,
                type: file.type,
                result: file.name,
                url: IMG_URL + response.filename,
              }],
            }));
          } else {
            alert('服务器异常');
          }
        });
        xhr.addEventListener('error', () => {
          alert('服务器异常');
        });
      });
    };
    return false;
  };

  handlePreview = (file) => {
    this.setState({
      preview: file.url || file.thumbUrl,
      visible: true,
    });
  };
  handleCancel=()=>{
    this.setState({
      visible: false,
    });
  }
  render() {
    const {editorState,preview, visible, imageList} = this.state;
    const propsImgs = {
      onRemove: (file) => {
        this.setState(({ imageList }) => {
          const index = imageList.indexOf(file);
          const newFileList = imageList.slice();
          newFileList.splice(index, 1);
          return { imageList: newFileList };
        });
      },
      beforeUpload: this.beforeUpload,
      fileList: this.state.imageList,
      onPreview: this.handlePreview,
      accept: 'image/*',
      listType: 'picture-card',
    };
    const uploadButton = (
      <div>
        <Icon type="plus"/>
        <div className="ant-upload-text">Upload</div>
      </div>
    );
    const formItemLayout = {
      labelCol: {
        xs: {span: 24},
        sm: {span: 7},
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 12},
        md: {span: 10},
      },
    };
    const {form: {getFieldDecorator, getFieldValue},active:{categoryList}} = this.props;
    return (
      <PageHeaderWrapper
        title="活动编辑"
      >
        <Form onSubmit={this.handleSubmit} hideRequiredMark style={{marginTop: 8}}>
          <Form.Item {...formItemLayout} label="活动type">
            {getFieldDecorator('article_type', {
              initialValue: this.state.article_type,
              rules: [
                {
                  required: true,
                  message: '活动type',
                },
              ],
            })(<Radio.Group>
              <Radio value={this.state.article_type}>{this.state.article_type}</Radio>
            </Radio.Group>)}
          </Form.Item>
          <Form.Item {...formItemLayout} label="标题">
            {getFieldDecorator('article_title', {
              initialValue: this.state.article_title,
              rules: [
                {
                  required: true,
                  message: '标题不能为空',
                },
              ],
            })(<Input placeholder="请输入标题"/>)}
          </Form.Item>
          {
            this.state.article_type=="活动预告"&&<div>
              <Form.Item {...formItemLayout} label="主讲人">
                {getFieldDecorator('article_speaker', {
                  initialValue: this.state.article_speaker,
                  rules: [
                    {
                      required: true,
                      message: '主讲人不能为空',
                    },
                  ],
                })(<Input placeholder="请输入主讲人"/>)}
              </Form.Item>
              <Form.Item {...formItemLayout} label="报名金额">
                {getFieldDecorator('article_attendPrice', {
                  initialValue: this.state.article_attendPrice
                })(<Input placeholder="请输入报名金额"/>)}
              </Form.Item>
              <Form.Item {...formItemLayout} label="关联文章">
                {getFieldDecorator('article_relatedActivity',{
                  initialValue: this.state.article_relatedActivity
                })(<Input placeholder="请输入报名数"/>)}
              </Form.Item>
              <Form.Item {...formItemLayout} label="报名数">
                {getFieldDecorator('article_maxAttendCount', {
                  initialValue: this.state.article_maxAttendCount
                })(<Input placeholder="请输入报名数"/>)}
              </Form.Item>
              <Form.Item {...formItemLayout} label="活动类别">
                {getFieldDecorator('article_category', {
                  initialValue: this.state.article_category,
                  rules: [
                    {
                      required: true,
                      message: '请选择活动类别',
                    },
                  ],
                })(<Select>
                  {categoryList.map(category => <Select.Option value={category.name}
                                                               key={category.categoryId}>{category.name}</Select.Option>)}
                </Select>)}
              </Form.Item>
              <Form.Item {...formItemLayout} label="活动开始时间">
                {getFieldDecorator('article_activityStartTime', {
                  initialValue:moment( this.state.article_activityStartTime, "YYYY-MM-DD HH:mm:ss"),
                  rules: [
                    {
                      required: true,
                      message: '请选择活动开始时间',
                    },
                  ],
                })(
                  <DatePicker showTime format="YYYY-MM-DD HH:mm:ss" style={{width: '100%'}} placeholder="请输入活动开始时间"/>
                )}
              </Form.Item>
              <Form.Item {...formItemLayout} label="活动举行时间">
                {getFieldDecorator('article_activityHoldTime', {
                  initialValue:moment( this.state.article_activityHoldTime, "YYYY-MM-DD HH:mm:ss"),
                  rules: [
                    {
                      required: true,
                      message: '请选择活动举行时间',
                    },
                  ],
                })(
                  <DatePicker showTime format="YYYY-MM-DD HH:mm:ss" style={{width: '100%'}} placeholder="请输入活动开始时间"/>
                )}
              </Form.Item>
              <Form.Item {...formItemLayout} label="活动结束时间">
                {getFieldDecorator('article_activityEndTime', {
                  initialValue:moment( this.state.article_activityEndTime, "YYYY-MM-DD HH:mm:ss"),
                  rules: [
                    {
                      required: true,
                      message: '请选择活动结束时间',
                    },
                  ],
                })(
                  <DatePicker showTime format="YYYY-MM-DD HH:mm:ss" style={{width: '100%'}} placeholder="请输入活动结束时间"/>
                )}
              </Form.Item>
              <Form.Item {...formItemLayout} label="活动下线时间">
                {getFieldDecorator('article_activityDownTime', {
                  initialValue:moment( this.state.article_activityDownTime, "YYYY-MM-DD HH:mm:ss"),
                  rules: [
                    {
                      required: true,
                      message: '请选择活动下线时间',
                    },
                  ],
                })(
                  <DatePicker showTime format="YYYY-MM-DD HH:mm:ss" style={{width: '100%'}} placeholder="请输入活动下线时间"/>
                )}
              </Form.Item>
              <Form.Item {...formItemLayout} label="活动标签">
                {getFieldDecorator('article_tag', {
                  initialValue: this.state.article_tag,
                  rules: [
                    {
                      required: true,
                      message: '活动标签不能为空',
                    },
                  ],
                })(<Input placeholder="多个，中文逗号隔开"/>)}
              </Form.Item>
              <Form.Item {...formItemLayout} label="地点">
                {getFieldDecorator('article_address', {
                  initialValue: this.state.article_address,
                  rules: [
                    {
                      required: true,
                      message: '活动地点',
                    },
                  ],
                })(<Input placeholder="活动地点不能为空"/>)}
              </Form.Item>
              <Form.Item {...formItemLayout} label="活动摘要">
                {getFieldDecorator('article_describe', {
                  initialValue: this.state.article_describe,
                  rules: [
                    {
                      required: true,
                      message: '活动摘要不能为空',
                    },
                  ],
                })(
                  <Input.TextArea
                    style={{minHeight: 32}}
                    placeholder="请输入活动摘要"
                    rows={4}
                  />,
                )}
              </Form.Item>
            </div>
          }

          <Form.Item {...formItemLayout} label="封面图">
            <div>
              <Upload {...propsImgs}>
                {
                  imageList.length >= 1 ? null : uploadButton
                }
              </Upload>
              <Modal visible={visible} footer={null} onCancel={this.handleCancel}>
                <img alt="example" style={{width: '100%'}} src={preview}/>
              </Modal>
            </div>
          </Form.Item>
        </Form>
        <div ref="editorElem" style={{textAlign: 'left'}}>
        </div>
        <FooterToolbar style={{ width:"100%" }}>
          {/*{this.getErrorInfo()}*/}
          <Button type="primary" onClick={()=>this.addArticle()}>
            提交
          </Button>
        </FooterToolbar>
        {/*<Button className={styles.addButton} onClick={() => this.addArticle()}>提交</Button>*/}
      </PageHeaderWrapper>
    );
  }
}
